# -*- coding: utf-8 -*-

import re
import time
import MySQLdb

from ndp.common import log_msg, req_option

class Cache(object):
	def __init__(self, url, index, ignored_column_list):
		self.index = index

		auth, db_info = url.split('@')

		self.login, self.password = auth.split(':')
		self.host, self.database, self.table = db_info.split('/')

		self.data = {}
		self.column_list = []

		self.ignored_column_list = ignored_column_list

		self.__readin()

#		self.last_update = time.time()

	def __cursor(self):
		c = MySQLdb.connect(self.host, self.login, self.password, self.database, charset='utf8').cursor()
		c.execute('SET NAMES "utf8";')

		log_msg('Created new MySQL connection, cursor is: %s' % c)

		return c

	def __readin(self):
		self.data.clear()

		while len(self.column_list) != 0:
			self.column_list.pop()

		cursor = self.__cursor()

		cursor.execute('SHOW COLUMNS FROM %s;' % self.table)

		for r in cursor.fetchall():
			self.column_list.append(str(r[0]))

		cursor.execute('SELECT * FROM %s;' % self.table)

		for r in cursor.fetchall():
			record = {}
			col_idx = 0

			for c in r:
				if self.column_list[col_idx] in self.ignored_column_list:
					col_idx += 1

					continue

				record[self.column_list[col_idx]] = c
				col_idx += 1

			self.data.setdefault(record[self.index], [])
			self.data[record[self.index]].append(record)

#		self.last_update = time.time()
		
	def put(self, record):
#		if self.last_update + 60 * 30 > time.time():
#			self.__readin()

		STATE_OK = 1

		for column in record.keys():
			if column in self.ignored_column_list:
				del record[column]
				continue

			if column in self.column_list:
				continue

			cursor = self.__cursor()

			if not 'item_' + column in req_option('allowed_column').split(','):
				del record['column']
				continue

			cursor.execute('ALTER TABLE %s ADD COLUMN %s VARCHAR(256);' % (self.table, column))

			STATE_OK = 0

		if not STATE_OK:
			cursor.connection.commit()

			self.__readin()
			STATE_OK = 1

		self.data.setdefault(record[self.index], [])		

		if record in self.data[record[self.index]]:
			return
		
		self.data[record[self.index]].append(record)

		cursor = self.__cursor()

		cursor.execute('INSERT INTO %s (%s) VALUES (%s)' % (self.table, ', '.join(record.keys()), ', '.join(['"%s"' % re.escape(i) for i in record.values()])))
		cursor.connection.commit()

	def get(self, query):
		if len(query) == 0:
			return []

#		if self.last_update + 60 * 30 > time.time():
#			self.__readin()
		# Sometimes it's better idea to sleep...
		return [e for e in (self.data[query[self.index]] if query[self.index] in self.data else []) if all((i in e and e[i] == query[i] for i in query))]	
		
